package com.jyb.qiyefuwu.uitls;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

public class EditTextUtils {
    /**
     * 设置EditText限制字数
     * @param editText EditText
     * @param textsize 显示字数和最大字数的Textview
     * @param wordLimitNum 最大字数限制
     */
    public static void setEditTextFlag(@Nullable EditText editText, TextView textsize, final int wordLimitNum){
        editText.addTextChangedListener(new TextWatcher() {
            //记录输入的字数
            private CharSequence enterWords;
            private int selectionStart;
            private int selectionEnd;
            private int enteredWords;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //实时记录输入的字数
                enterWords= charSequence;
            }

            @Override
            public void afterTextChanged(Editable s) {
                //已输入字数
                enteredWords= wordLimitNum - s.length();
                //TextView显示剩余字数
                if(textsize!=null) {
                    textsize.setText((wordLimitNum-enteredWords) + "/" + wordLimitNum );
                }
                selectionStart =  editText.getSelectionStart();
                selectionEnd =  editText.getSelectionEnd();
                if (enterWords.length() > wordLimitNum) {
                    //删除多余输入的字（不会显示出来）
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    editText.setText(s);
                    //设置光标在最后
                    editText.setSelection(tempSelection);
                }
            }
        });
    }
}
